/*
	网站页面控制器
*/
var avPage			= AV.Object.extend("Page");
var avArticle		= AV.Object.extend("Article");
var avContentGroup	= AV.Object.extend("ContentGroup");

var moment		= require('moment');
var fs 			= require('fs');
var mdCommon	= require('cloud/modules/common.js');

var display		= function(res,tplFile,data) {
	data.moment		= moment;
	data.layout		= false;
	mdCommon.display(res,tplFile,data);
}

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
exports.homePage = function(req,res) {
	//res.redirect("/index");
	res.redirect("/index.html");
	//display(res,'index',{res:res});
}

/**
 * 静态页面
 * 2015.04.20  by 胡斌
 */
exports.htmlPage = function(req,res) {
	var path	= req.path.split("/");
	var fn		= path[path.length-1];
	var type	= fn.split(".");
	display(res,type[0],{res:res});
}

/**
 * ajax
 * 2015.06.04  by 胡斌
 */
exports.Ajax = function(req,res) {
	var returnData	= {};
	var group	= req.query.group?req.query.group.split(","):[];
	var ids		= req.query.ids?req.query.ids.split(","):[];
	var limit	= req.query.limit?req.query.limit:1;
	var page	= req.query.page?req.query.page:1;
	var key		= req.query.where;
	var orderby	= req.query.page?req.query.orderby:"sort,-createdAt";
	//console.dir(ids);
	if(ids.length>0){
		var type=req.query.type?req.query.type:"Article";
		AV.Query.doCloudQuery("select count(*),include cover,* from "+type+" where objectId in ('"+ids.join("','")+"') limit "+(page*limit-limit)+","+limit+"  order by "+orderby).then(function(object){
			var results=object.results;
			returnData=object;
			for(var i=0;i<results.length;i++){
				returnData.results[i].set("coverUrl",results[i].get("cover").get("url"));
			}
			res.json(returnData);
		},function(error){
			returnData.error=error;
			res.json(returnData);
		});
	}else if(group.length>0){
		AV.Query.doCloudQuery("select count(*),type from ContentGroup where name in ('"+group.join("','")+"')").then(function(object){
			var results=object.results;
			//console.dir(object);
			if(results.length>0){
				var type=[],groupID=[];
				for(var i=0;i<results.length;i++){
					if(type.indexOf(results[i].get("type"))==-1){
						type.push(results[i].get("type"));
					}
					groupID.push(results[i].id);
				}
				if(type.length==1){
					return AV.Query.doCloudQuery("select count(*),include cover,* from "+type[0]+" where ContentGroup in ('"+groupID.join("','")+"') limit "+(page*limit-limit)+","+limit+"  order by "+orderby);
				}else{
					return AV.Promise.error({"message":"请确保对象类型一致！"});
				}
			}else{
				return AV.Promise.error({"message":"找不到对应的内容组！"});
			}
		}).then(function(object){
			var results=object.results;
			returnData=object;
			for(var i=0;i<results.length;i++){
				returnData.results[i].set("coverUrl",results[i].get("cover").get("url"));
			}
			res.json(returnData);
		},function(error){
			returnData.error=error;
			res.json(returnData);
		});
	}else{
		returnData.error={};
		returnData.error.message="缺少必要的参数：group！";
		res.json(returnData);
	}



}

/**
 * 网站通用页面
 * 2015.05.05  by 胡斌
 */
exports.Page = function(req,res,next){
	var name=req.path.replace("/","");
	var data={},queryContent,queryContentArr=[],ContentGroupKeyArr=[];
	var pagesize	= req.query.pagesize;
	if(name=="admin-login"){
		next();
	}else{
		var queryPage 	= new AV.Query(avPage);
		queryPage.equalTo("name",name);
		queryPage.include("Templet");
		queryPage.first().then(function(result){
			if(typeof(result)=="object"){
				data.result				= result;	//页面数据
				var ContentGroup		= data.result.get("ContentGroup");
				if(typeof(ContentGroup)!="undefined"){
					var queryContentGroup 	= new AV.Query(avContentGroup);
					queryContentGroup.equalTo("objectId",ContentGroup);
					return queryContentGroup.first();
				}else{
					return AV.Promise.as(false);
				}
			}else{
				return AV.Promise.error(404);
			}
		}).then(function(result) {
			if(result && typeof(result)!="undefined"){
				if(typeof(pagesize)=="undefined"){pagesize=result.get("perPage");}
				data.ContentGroup=result;//主内容组数据
				if(result.get("type")=="Article"){
					queryContent 		= new AV.Query(avArticle);
				}else{
					queryContent 		= new AV.Query(avArticle);
				}
				queryContent.contains("ContentGroup",result.id);
				return queryContent.count();
			}else{
				return AV.Promise.as(0);
			}
		}).then(function(result) {
			data.pager	= mdCommon.Paginate(req.query.page, pagesize, result);//主内容的分页数据
			if(result!=0){
				queryContent.include("cover");
				queryContent.ascending("sort");
				queryContent.addDescending("createdAt");
				queryContent.skip((data.pager.currentPage-1)*data.pager.pagesize);
				queryContent.limit(data.pager.pagesize);
				return queryContent.find();
			}else{
				return AV.Promise.as([]);
			}
		}).then(function(results) {
			data.results	= results;//主内容列表数据

			//console.dir(data.results[0].attributes);

			var ContentGroupArr	= data.result.get("ContentGroupArr");
			if(typeof(ContentGroupArr)=="undefined")ContentGroupArr=[];

			var queryContentGroup 	= new AV.Query(avContentGroup);
			queryContentGroup.containedIn("objectId",ContentGroupArr);
			return queryContentGroup.find();
		}).then(function(results) {
			var pomiseArr=[];
			if(results.length>0){
				for(var i=0;i<results.length;i++){
					if(results[i].get("type")=="Article"){
						queryContentArr[i] 	= new AV.Query(avArticle);
						queryContentArr[i].include("cover");
					}else{
						queryContentArr[i] 	= new AV.Query(avArticle);
						queryContentArr[i].include("cover");
					}
					queryContentArr[i].contains("ContentGroup",results[i].id);
					queryContentArr[i].limit(results[i].get("perPage"));
					queryContentArr[i].ascending("sort");
					queryContentArr[i].addDescending("createdAt");
					ContentGroupKeyArr[i]=results[i].get("name");
					pomiseArr[i]=queryContentArr[i].find();
				}
			}

			AV.Promise.all(pomiseArr).then(function(values) {
				var Groups={};
				for(var i=0;i<values.length;i++){
					Groups[ContentGroupKeyArr[i]]=values[i];
				}
				data.groups	= Groups;//副内容的分页数据
				data.User	= req.AV.user;
				var Templet=data.result.get("Templet");
				display(res,Templet.get("cacheName"),data);
			}, function(error){
				console.err("pageName="+name+" | error:"+error.message);
				var Templet	= data.result.get("Templet");
				data.User	= req.AV.user;
				//console.dir(req.AV.user);
				display(res,Templet.get("cacheName"),data);
			});
		},function(error){
			if(error==404){
				next();
			}else{
				display(res,"message",{
					user:req.AV.user,
					result:req.AV.user,
					message:error
				});
			}
		});
	}
}

/**
 * 内容详情页面
 * 2015.05.18  by 胡斌
 */
exports.View = function(req,res,next) {
	var data={},Templet;
	var path	= req.path.split("/");
	var id		= req.query.id;
	var name	= req.query.group;


	if(typeof(name)=="undefined"){name="-1";}
	var query	= new AV.Query(avContentGroup);

	//var name	= path[1];

	query.equalTo("name",name);
	query.include("Templet");
	query.first().then(function(result){
		if(typeof(result)=="object"){
			Templet=result.get("Templet");
			var queryArticle 	= new AV.Query(avArticle);
			queryArticle.include("cover");
			return queryArticle.get(id);
		}else{
			return AV.Promise.error(404);
		}
	}).then(function(result) {
		if(typeof(result)!="undefined"){
			data.result	= result;
			data.User	= req.AV.user;
			display(res,Templet.get("cacheName"),data);
		}else{
			next();
		}
	},function(error) {
		if(error==404){
			next();
		}else{
			display(res,"message",{
				user:req.AV.user,
				result:req.AV.user,
				message:error
			});
		}
	});
}
